<template>
  <div class="main">
    <!-- 标题 -->
    <p>角色列表</p>
    <!-- 工具栏 -->
    <div class="tabBar">
      <div class="btns">
        <el-button type="info" size="small" @click="reflash">刷新</el-button>
        <el-button type="primary" size="small" @click="handleAdd"
          >新增</el-button
        >
        <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          icon="WarnTriangleFilled"
          icon-color="orange"
          title="你确定要删除全部选中的吗?"
          @confirm="handleDeleteAll"
        >
          <template #reference>
            <el-button type="danger" size="small" :disabled="isSelect"
              >批量删除</el-button
            >
          </template>
        </el-popconfirm>
      </div>
      <div class="search">
        <el-input
          ref="searchRef"
          v-model="searchValue"
          type="text"
          placeholder="请输入你要查询的用户名"
          size="small"
          clearable
          @keyup.enter="changeValue"
        />
        <el-button type="warning" size="small" @click="changeValue"
          >搜索</el-button
        >
        <el-button
          type="primary"
          size="small"
          :loading="exportLoading"
          @click="doExport"
          >导出Excel数据</el-button
        >
      </div>
    </div>
    <!-- 表格 -->
    <el-table
      class="tabel"
      ref="multipleTableRef"
      :data="filterDate"
      style="width: 100%"
      v-loading="flag"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" width="55" />
      <el-table-column
        width="auto"
        v-for="(item, index) in tabelDateTitle"
        :prop="item.propName"
        :label="item.label"
        ><template #default="{ row }" v-if="slotName[index] === 'headImg'"
          ><img class="headImg" :src="row.headImg" /></template
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="140" class="setBtn">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEidt(row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="WarnTriangleFilled"
            icon-color="orange"
            title="你确定要删除吗?"
            @confirm="handleDeleteOne(row)"
          >
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="fenye"
      v-model:current-page="query.page"
      v-model:page-size="query.size"
      :page-sizes="pageSizes"
      layout="total,jumper, prev, pager, next, sizes"
      :total="total"
    />
    <MyUserDialog @editOrAdd="handleEditOrAdd" />
  </div>
</template>
<script>
import eventBus from "@/utils/eventBus";
import MyTree from "@/components/MyTree.vue";
import MyUserDialog from "@/components/MyUserDialog.vue";
import { getUserPageAPI, getUserDeleteAPI } from "@/api/userList";
import { ElMessage } from "element-plus";
// import ExportJsonExcel from "js-export-excel";
import { exportTabel } from "@/utils/exportTabel";
export default {
  name: "tabelItem",
  inheritAttrs: false, //阻止组件继承属性
  components: {
    MyTree,
    MyUserDialog,
  },
  data: () => {
    return {
      //绑定搜索框
      searchValue: "",
      // 表格标题
      tabelDateTitle: [
        {
          propName: "headImg",
          label: "头像",
        },
        {
          propName: "username",
          label: "用户名",
        },
        {
          propName: "name",
          label: "姓名",
        },
        {
          propName: "nickName",
          label: "昵称",
        },
        {
          propName: "roleName",
          label: "角色",
        },
        {
          propName: "status",
          label: "状态",
        },
        {
          propName: "phone",
          label: "手机号码",
        },
        {
          propName: "remark",
          label: "备注",
        },
        {
          propName: "createTime",
          label: "创建时间",
        },
      ],
      //表格数据
      tabelDate: [],
      //筛选存储数据
      filterDate: [],
      //是否加载加载条
      flag: false,
      slotName: [], //插槽名
      exportLoading: false, //导出数据的loading
      searchValue: "", //搜索框的值
      selectIds: [], //存储表格选中项ID
      //分页数据
      total: 0,
      query: {
        page: 2,
        size: 5,
      },
      showNumber: 5, //每页显示的条数
      pageSizes: [5, 10, 15, 20],
    };
  },
  watch: {
    query: {
      handler() {
        this.reflash();
      },
      deep: true,
    },
  },
  mounted() {
    this.getSlotName();
    this.reflash();
  },
  computed: {
    isSelect() {
      return this.selectIds.length === 0 ? true : false;
    },
  },
  methods: {
    //刷新数据
    reflash() {
      this.getRoleList();
    },

    //动态渲染插槽
    getSlotName() {
      this.slotName = Object.values(this.tabelDateTitle).map(
        ({ propName }) => propName
      );
    },

    //新增和编辑的操作
    async handleEditOrAdd(payload) {
      this.getRoleList();
      if (payload.id) {
        ElMessage.success("编辑成功");
      } else {
        ElMessage.success("新增成功");
      }
    },

    //修改搜索框的值
    changeValue() {
      const searchDom = this.$refs.searchRef;
      let value = searchDom.input.value;
      if (value) {
        this.filterDate = this.filterDate.filter((item) =>
          item.name.includes(value)
        );
      } else {
        this.filterDate = this.tabelDate;
      }
    },

    //表格新增事件
    handleAdd() {
      const form = {
        id: 0, //用于判断是新增(0)还是编辑
        headImg: "",
        name: "",
        label: "",
        remark: "",
        menuIdList: [],
        username: "",
        password: "",
        nickName: "",
        phone: "",
        email: "",
        //角色数组
        roleName: [],
        //状态选择单选框
        status: 0,
      };
      //组装数据
      const obj = {
        form,
        dialogTitle: "新增",
        showFlag: true,
      };
      eventBus.emit("showDialog", obj);
      this.reflash();
    },

    //表格编辑事件(编辑设置消息回填)
    handleEidt(row) {
      console.log(row);
      const obj = {
        form: row,
        dialogTitle: "编辑",
        showFlag: true,
      };
      eventBus.emit("showDialog", obj);
      this.reflash();
    },

    //表格删除单个事件
    async handleDeleteOne(row) {
      await getUserDeleteAPI({ ids: [row.id] });
      ElMessage.success("删除成功");
      //刷新数据
      this.reflash();
    },

    //表格删除选中事件
    async handleDeleteAll() {
      await getUserDeleteAPI({ ids: this.selectIds });
      ElMessage.success("删除成功");
      //刷新数据
      this.reflash();
    },

    //多选框的变化事件
    handleSelectionChange(selection) {
      const ids = [];
      const result = selection.filter((item) => ids.push(item.id));
      this.selectIds = result;
    },

    //分页
    //获取角色数据
    async getRoleList() {
      this.flag = true;
      let { list, pagination } = await getUserPageAPI(this.query);
      this.filterDate = this.tabelDate = list;
      this.total = pagination.total;
      if (this.filterDate && this.tabelDate) {
        this.flag = false;
      }
    },

    handleSizeChange(val) {
      console.log(`${val} items per page`);
    },
    handleCurrentChange(val) {
      console.log(`current page: ${val}`);
    },

    //导出excel数据
    doExport() {
      //从表格数据里面解构出需要导出的表头标题
      const {
        id,
        headImg,
        name,
        label,
        remark,
        menuIdList,
        username,
        password,
        nickName,
        phone,
        email,
        roleName,
        status,
      } = this.$attrs.tabelDate;
      exportTabel(this.$attrs.tabelDate, {
        id,
        headImg,
        name,
        label,
        remark,
        menuIdList,
        username,
        password,
        nickName,
        phone,
        email,
        roleName,
        status,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  // height: calc(100% - 150px);
  padding: 0 20px;
  box-sizing: border-box;
  overflow: hidden;
  p {
    text-align: center;
    font-weight: bold;
    margin: 0;
  }
  .tabBar {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      margin-left: auto;
      .el-input {
        width: 150px;
      }
    }
  }
  .tabel {
    height: 500px;
    overflow-y: auto;
  }
  .fenye {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
  .tree {
    width: 100%;
    height: 150px;
    padding: 5px;
    box-sizing: border-box;
    border-radius: 5px;
    overflow-y: auto;
    border: 1px solid #cccccc;
  }
  .headImg {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
}
</style>
